package org.me.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.me.ttvdroid.TotalView;

/**
 *
 * @author peterholtegaard@gmail.com
 */
public class NetworkDataProvider extends Activity {

    private Context c;
    private String sessionID;
    private static NetworkDataProvider instance = null;
    private final String TotalView_URL = "http://80.63.35.60/agentops/";
    private boolean isAuthed = false;
    private static final String PREFS_NAME = "preferences";

    /**
     * @param args the command line arguments
     */
    private NetworkDataProvider() {
    }

    public static NetworkDataProvider getInstance() {
        if (instance == null) {
            instance = new NetworkDataProvider();
        }
        return instance;
    }

    public String getDayAsHtml(int year, int month, int dayOfMonth) {
        String fMonth = month < 10 ? "0" + String.valueOf(month) : String.valueOf(month);
        String fDay = dayOfMonth < 10 ? "0" + String.valueOf(dayOfMonth) : String.valueOf(dayOfMonth);
        String dayURL = String.valueOf((year - 1999) * 10) + fMonth + fDay;
        Log.e("slår op på", dayURL);
        String targetURL = TotalView_URL + "displayMyScheduleAction.do;jsessionid=" + sessionID + "?startDay=" + dayURL + "&viewFormat=daily";
        try {
            boolean relevant = false;
            InputStream is = getInputStreamFromUrl(targetURL, "");
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                if (relevant) {
                    response.append(line);
                    if (line.contains("</table>")) {
                        relevant = false;
                    }
                } else if (line.contains("name=\"offeredSchedDateArray\"")) {
                    relevant = true;
                }


            }

            return response.toString();
        } catch (Exception e) {
            return "error";
        }

    }

    public String getMonthAsHtml(String month, int year) {
        String startDay = String.valueOf((year - 1999) * 10) + month + "01";
        String targetURL = TotalView_URL + "displayMyScheduleAction.do;jsessionid=" + sessionID + "?startDay=" + startDay + "&viewFormat=monthly";
        try {
            //Create connection
            Log.e("forsøger log in med", targetURL);
            InputStream is = getInputStreamFromUrl(targetURL, "");
            if (is == null) {
                return "pauseskærm";
            }
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = rd.readLine()) != null) {

                if (line.contains("class=\"calempty\"")) {// || line.contains("class=\"calunack\"")) {
                    response.append(line).append("\n");
                }
            }
            rd.close();
            if (response.toString().equals("")) {
                return "kunne ikke hente totalview data";
            }

            return response.toString();
        } catch (Exception e) {
            return "black eyed peas";

        }
    }

    public void logIn() {
        SharedPreferences settings = TotalView.getPrefs();
        String uName = settings.getString("userName", "");
        String pWord = settings.getString("password", "");
        logIn(uName, pWord);
    }

    public void logIn(String username, String password) {

        if (!isAuthed) {
            String url = TotalView_URL + "signin.do";
            InputStream content = null;
            try {
                DefaultHttpClient httpclient = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost(url);
                List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
                //this is where you add your data to the post method
                nameValuePairs.add(new BasicNameValuePair(
                        "userName", username));
                nameValuePairs.add(new BasicNameValuePair("password", password));
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httpPost);
                List<Cookie> cookies = httpclient.getCookieStore().getCookies();
                if (cookies.isEmpty()) {
                    Log.e("cookies: ", "None");
                } else {
                    for (int i = 0; i < cookies.size(); i++) {
                        Log.e("cookie: ", " - " + cookies.get(i).toString());
                        if (cookies.get(i).getName().equals("JSESSIONID")) {
                            sessionID = cookies.get(i).getValue();
                        }
                    }
                }
                Header[] headers = response.getAllHeaders();
                for (int i = 0; i < headers.length; i++) {
                    String nameValue = headers[i].getName() + " : " + headers[i].getValue();
                    Log.e("header", nameValue);
                }
                Log.e("er logget på", String.valueOf(isAuthed));
                isAuthed = true;

                //content = response.getEntity().getContent();

                // return content;
            } catch (Exception e) {
                Log.e("huh?", e.getMessage());
                //return null;
            }
        } else {
            //Log.e("er logget på", String.valueOf(isAuthed));
            isAuthed = false;
            logIn(username, password);

        }

    }

    public InputStream getInputStreamFromUrl(String url, String urlParameters) {
        InputStream content = null;
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
            HttpResponse response = httpclient.execute(httpPost);
            content = response.getEntity().getContent();
            return content;
        } catch (Exception e) {
            return null;
        }
    }
}
